package com.mobile.collect.present;

import android.text.TextUtils;

import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.mobile.collect.AddPointEvent;
import com.mobile.collect.activitys.CollectApplication;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.net.BaseObjBean;
import com.mobile.collect.utils.AppContents;

import org.json.JSONException;

import java.io.File;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.List;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.kit.NToast;
import cn.droidlover.xdroidmvp.mvp.IView;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import cn.droidlover.xdroidmvp.net.NetError;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class BasePresent<V extends IView> extends XPresent<V> {
    public Consumer failConsumer;
    public Consumer failNeedLoginConsumer;
    public Consumer failNotDealConsumer;

    public BasePresent() {
        failConsumer = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                if (throwable != null && throwable instanceof NetError) {
                    dealFailResult((NetError) throwable);
                }
                throwable.printStackTrace();
                getV().disLoadDialog();
                getV().loadFail();
            }
        };
        failNeedLoginConsumer = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) {
                e.printStackTrace();
                NetError error = null;
                if (e != null) {
                    if (!(e instanceof NetError)) {
                        if (e instanceof UnknownHostException) {
                            error = new NetError("请检查网络连接", NetError.NoConnectError);
                        } else if (e instanceof JSONException
                                || e instanceof JsonParseException
                                || e instanceof JsonSyntaxException) {
                            error = new NetError(e, NetError.ParseError);
                        } else if (e instanceof ConnectException) {
                            error = new NetError("请检查网络连接", NetError.NoConnectError);
                        } else {
                            error = new NetError(e, NetError.ParseError);
                        }
                    } else {
                        error = (NetError) e;
                    }
                    dealFailResult(error);
                }
                getV().disLoadDialog();
                getV().loadFail();
            }
        };
        failNotDealConsumer = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {

            }
        };
    }

    public Consumer getFailNeedLoginConsumer() {
        return failNeedLoginConsumer;
    }

    public void dealFailResult(NetError error) {
        error.printStackTrace();
        if (error.getType() == NetError.AuthError) {
            SharedPref.getInstance(CollectApplication.getContext()).putString(AppContents.TOKEN, "");
            getV().toLogin();
        } else {
            String message = error.getMessage();
            if (!TextUtils.isEmpty(message)) {
                NToast.shortToast(message);
            }
        }
    }


    public abstract class SuccessConsumer<T> implements Consumer<BaseObjBean> {
        @Override
        public void accept(BaseObjBean objBean) {
            getV().disLoadDialog();
            getV().showMainView();
            T t = (T) objBean.getData();
            accept2(t);
        }

        public abstract void accept2(T t);
    }

    public abstract class SuccessConsumer2<T> implements Consumer<BaseObjBean> {
        @Override
        public void accept(BaseObjBean objBean) {
            getV().disLoadDialog();
        }

    }


    public String getToken() {
        String token = SharedPref.getInstance(CollectApplication.getContext()).getString(AppContents.TOKEN, "");
        return token;
    }

    public boolean isLogin() {
        return !TextUtils.isEmpty(getToken());
    }

    public static MultipartBody filesToMultipart2Body(List<String> list) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        for (String path : list) {
            File file = new File(path);
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            builder.addFormDataPart(file.getName(), file.getName(), requestBody);
        }

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    public static MultipartBody filesToMultipartBody(String token, String path, String fileType) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file = new File(path);
        String mediaType;
        switch (fileType) {
            case "xls":
                mediaType = "application/x-xls";
                break;
            case "zip":
                mediaType = "application/zip";
                break;
            case "jpeg":
                mediaType = "image/jpeg";
                break;
            default:
                mediaType = "application/octet-stream";
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse(mediaType), file);
        builder.addFormDataPart("file", file.getName(), requestBody);
        builder.addFormDataPart("token", token);
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }


    public void sendPointChagneEvent(Long deviceInfoId, Long picInfoId) {

        if (null != picInfoId) {
            DevicePicInfo devicePicInfo = EntityManager.getInstance().queryDevicePicIById(picInfoId);
            if (null != devicePicInfo) {
                long pointCount = EntityManager.getInstance().queryDevicePointInfosByPicId(picInfoId);
                devicePicInfo.setPointCount(pointCount);
                EntityManager.getInstance().saveDevicePicInfo(devicePicInfo);
            }
        }
        if (deviceInfoId !=null) {
           DeviceInfo deviceInfo = EntityManager.getInstance().queryDeviceInfoById(deviceInfoId);
            if (null != deviceInfo) {
                long allPointCount = EntityManager.getInstance().queryDevicePointInfoByDeviceId(deviceInfoId);
                deviceInfo.setPointCount(allPointCount);
                EntityManager.getInstance().saveDeviceInfo(deviceInfo);
            }
        }
        AddPointEvent addPointEvent = new AddPointEvent();
        addPointEvent.setPidDbId(deviceInfoId);
        BusProvider.getBus().post(addPointEvent);
    }


    private int countPicPoint(DevicePicInfo picInfo) {
        List<DevicePointInfo> pointInfos = picInfo.getPointList();
        int count = 0;
        for (DevicePointInfo pointInfo : pointInfos) {
            String childTypeEn = pointInfo.getChildTypeEn();
            if ("KP".equals(childTypeEn)) {
                count += pointInfo.getDeviceCount();
            } else {
                count++;
            }
        }
        return count;
    }

}
